'use strict';

const BaseService = require('../base');
const { OrderStatusEnum, BalanceLogTypeEnum, RefundStatusEnum} = require('../../utils/enum');
const dayjs = require('dayjs');
const { Op } = require('sequelize');
/**
 * 生成旅游订单号
 * @return {string}
 */
function generateTravelOrderNo(prefix = 'TO') {
    const now = dayjs();
    // 生成格式：年月日时分秒+4位随机数
    return prefix + now.format('YYYYMMDDHHmmss') + Math.floor(Math.random() * 10000).toString().padStart(4, '0');
}

// 获取SKU名称
function getSkuName(sku) {
    console.log('sku', sku);
    if (!sku || !sku.spec_combination) return '';

    try {
        const specCombination = JSON.parse(sku.spec_combination);
        const specNames = Object.values(specCombination).map(value => value.replace(/,/g, '|'));
        return ('-'  + specNames.join(' | '));
    } catch (error) {
        console.error('解析SKU规格失败:', error);
        return '';
    }
}
class TravelOrderService extends BaseService {
    static get modelName() {
        return 'Business.TravelOrder';
    }

    getPageInclude() {
        return [
            {
                model: this.ctx.model.Business.User,
                as: 'user',
            },
            {
                model: this.ctx.model.Business.TravelOrderItem,
                as: 'travelOrderItems',
            },
            {
                model: this.ctx.model.Business.User,
                as: 'shareUser',
            },
        ]
    }

    getListInclude() {
        return this.getPageInclude()
    }

    getDetailInclude() {
        return [
            ...this.getPageInclude(),
            {
                model: this.ctx.model.Business.Travel,
                as: 'travel',
            },
            // travel_sku_stock_id
            {
                model: this.ctx.model.Business.TravelSkuStock,
                as: 'travelSkuStock',
            }
        ]
    }
    /**
     * 拼团订单的，团列表
     */
    async getGroupList() {
        const { ctx } = this;
        const result = await ctx.model.Business.TravelOrder.findAll({
            where: {
                is_group: 1
            },
            include: [
                // 团期
                {
                    model: this.ctx.model.Business.TravelSkuStock,
                    as: 'travelSkuStock',
                    attributes: ['id', 'travel_date', 'group_adult_people', 'adult_price', 'child_price']
                },
                {
                    model: this.ctx.model.Business.Travel,
                    as: 'travel',
                    attributes: ['id', 'name', 'cover']
                }
            ],
            // 排序 按travel_date从近到远
            order: [['travel_date', 'ASC']],
            // 订单退款状态=
            attributes: [
                'travel_sku_stock_id',
                [this.ctx.model.Sequelize.fn('SUM', this.ctx.model.Sequelize.literal('CASE WHEN TravelOrder.status = \'paid\' AND TravelOrder.refund_status = -1 THEN TravelOrder.count ELSE 0 END')), 'groupPeople']
            ],
            group: ['travel_sku_stock_id'],
        })
        return result;
    }

    /**
     * 创建旅游订单
     * @param {Object} orderData - 订单数据
     * @return {Promise<*>}
     */
    async create(orderData) {
        const { ctx } = this;
        /**
         * 校验用户
         */
        if (!orderData.user_id) throw new Error('用户不存在');
        // 检查用户是否存在
        const user = await ctx.model.Business.User.findOne({
            where: {
                id: orderData.user_id
            }
        })
        if (!user) {
            throw new Error('用户不存在');
        }
        if (!user.status) {
            throw new Error('用户已禁用');
        }

        // 验证旅游特有字段
        if (!orderData.adult_count && !orderData.child_count) {
            throw new Error('成人数量和儿童数量不能同时为0');
        }
        let travelers = []
        // 处理人员列表
        if (orderData.travelers) {
            travelers = JSON.parse(orderData.travelers);
            let traveler = travelers.find(item => item.type === 'adult')
            if (traveler) {
                orderData.contact_name = traveler.name
                orderData.contact_phone = traveler.phone
            }
        }
        const travel = await ctx.model.Business.Travel.findOne({
            where: {
                id: orderData.travel_id
            }
        })
        if (!travel) {
            throw new Error('旅游产品不存在');
        }
        const sku = await ctx.model.Business.TravelSku.findOne({
            where: {
                id: orderData.travel_sku_id
            }
        })
        if (!sku) {
            throw new Error('旅游产品SKU不存在');
        }
        const skuStock = await ctx.model.Business.TravelSkuStock.findOne({  
            where: {
                id: orderData.travel_sku_stock_id
            }
        })
        if (!skuStock) {
            throw new Error('旅游产品线路日期不存在');
        }
        const transaction = await ctx.model.transaction();
        try {
            // 1. 生成订单号
            const orderNo = generateTravelOrderNo();
            // 2. 创建主订单
            let createData = {
                order_no: orderNo,
                ...orderData,
                status: Number(orderData.payment_amount) === 0 ? OrderStatusEnum.PAID : OrderStatusEnum.PENDING,
                travel_id: orderData.travel_id,
                travel_sku_id: orderData.travel_sku_id,
                travel_sku_stock_id: orderData.travel_sku_stock_id,
                travel_name: `${travel.name} ${getSkuName(sku)}`,
                travel_cover: travel.cover,
                sku_spec: sku.spec_combination,
            }
            if (user.parent_user_id) {
                const parentUser = await ctx.model.Business.User.findOne({
                    where: {
                        id: user.parent_user_id
                    }
                })
                if (parentUser && parentUser.user_type === 3) {
                    createData.travel_share_user_id = user.parent_user_id
                    createData.travel_share_price = sku.share_price
                    createData.travel_share_price2 = sku.share_price2
                }
            }
            console.log(createData,'创建订单数据')
            // 4. 创建订单
            const order = await ctx.model.Business.TravelOrder.create(createData, { transaction });
            // travelers
            for (let i = 0; i < travelers.length; i++) {
                const traveler = travelers[i];
                let price = 0
                if (traveler.type === 'adult') {
                    price = orderData.adult_price
                } else if (traveler.type === 'child') {
                    price = orderData.child_price
                }
                await ctx.model.Business.TravelOrderItem.create({
                    traveler_name: traveler.name,
                    traveler_id_card: traveler.id_card,
                    traveler_phone: traveler.phone,
                    traveler_type: traveler.type,
                    travel_order_id: order.id,
                    travel_id: orderData.travel_id,
                    travel_sku_id: orderData.travel_sku_id,
                    travel_sku_stock_id: orderData.travel_sku_stock_id,
                    travel_name: `${travel.name} ${getSkuName(sku)}`,
                    travel_cover: travel.cover,
                    sku_spec: sku.spec_combination,
                    price: price,
                    count: 1,
                    total_amount: price,
                }, { transaction });
            }
            
            if (orderData.travel_share_order_id) {  
                const shareOrder = await ctx.model.Business.TravelShareOrder.findOne({
                    where: {
                        id: orderData.travel_share_order_id
                    },
                    transaction
                })
                if (!shareOrder) {
                    throw new Error('代付订单不存在');
                }
                if (shareOrder.user_id) {
                    throw new Error('代付订单已失效');
                }
                await shareOrder.update({
                    user_id: order.user_id
                }, { transaction })
            }
            await transaction.commit();
            // 6. 返回订单信息
            return order
        } catch (error) {
            console.log(error)
            await transaction.rollback();
            throw error;
        }
    }

    /**
     * 取消旅游订单
     * @param {Object} params - 参数
     * @return {Promise<boolean>}
     */
    async cancel(params) {
        const { ctx } = this;
        const { id } = params;
        const transaction = await ctx.model.transaction();

        try {
            // 1. 查询订单
            const order = await this.ctx.model.Business.TravelOrder.findOne({
                where: {
                    id,
                },
            });

            if (!order) {
                throw new Error('订单不存在');
            }
            const user = await this.ctx.model.Business.User.findOne({
                where: {
                    id: order.user_id
                }
            })
            if (!user) {
                throw new Error('用户不存在');
            }
            // 2. 判断订单状态
            if (order.status !== OrderStatusEnum.PENDING && order.status !== OrderStatusEnum.PENDING_PRICING) {
                throw new Error('只有未支付的订单才能取消');
            }
            // 5. 更新订单状态
            await order.update({
                status: OrderStatusEnum.CANCELLED,
                cancel_time: new Date(),
            }, { transaction });
            if (order.travel_share_order_id) {
                const shareOrder = await this.ctx.model.Business.TravelShareOrder.findOne({
                    where: {
                        id: order.travel_share_order_id
                    }
                })
                if (shareOrder) {
                    await this.ctx.service.business.travelShareOrder.cancelOrder(shareOrder, transaction)
                }
            }
            await transaction.commit();
            return true;
        } catch (error) {
            await transaction.rollback();
            throw error;
        }
    }

    /**
     * 设置旅游订单价格
     * @param {Object} params - 参数
     * @return {Promise<boolean>}
     */
    async setPrice(params) {
        const { ctx } = this;
        const { order_id, store_id, amount } = params;
        const transaction = await ctx.model.transaction();

        try {
            // 1. 查询订单
            const order = await this.ctx.model.Business.TravelOrder.findOne({
                where: {
                    id: order_id,
                    store_id: store_id
                },
            });

            if (!order) {
                throw new Error('订单不存在或无权限操作');
            }

            // 2. 验证工坊权限
            const store = await this.ctx.model.Business.Store.findOne({
                where: {
                    id: store_id
                }
            });

            if (!store) {
                throw new Error('工坊不存在');
            }

            // 3. 判断订单状态
            if (order.status !== OrderStatusEnum.PENDING_PRICING && order.status !== OrderStatusEnum.PENDING) {
                throw new Error('只有待定价或待支付的订单才能设置价格');
            }

            // 4. 验证价格
            const price = parseFloat(amount);
            if (isNaN(price) || price <= 0) {
                throw new Error('价格必须大于0');
            }

            // 5. 更新订单价格和状态
            await order.update({
                amount: price,
                payment_amount: price,
                status: OrderStatusEnum.PENDING,
                update_time: new Date(),
            }, { transaction });

            await transaction.commit();
            return true;
        } catch (error) {
            await transaction.rollback();
            throw error;
        }
    }

    /**
     * 申请退款
     * @param {Object} params - 参数
     * @return {Promise<boolean>}
     */
    async refund(params) {
        const { ctx } = this;
        const { id, refund_reason, is_admin = false } = params;
        const transaction = await ctx.model.transaction();

        try {
            // 查询订单
            const order = await this.ctx.model.Business.TravelOrder.findOne({
                where: { id }
            });

            if (!order) {
                throw new Error('订单不存在');
            }
            if (order.payment_status !== 1) {
                throw new Error('订单未支付');
            }
            // 出行日期是否大于
            if (dayjs(order.travel_date).isBefore(dayjs())) {
                throw new Error('出行日期已过，无法退款');
            }
            if (order.refund_status === RefundStatusEnum.REFUNDING) {
                throw new Error('订单已申请退款');
            }
            if (order.refund_status === RefundStatusEnum.SUCCESS) { 
                throw new Error('订单已退款');
            }
            // 判断订单状态 //只有支付过的订单才能付款
            const refund_amount = params.refund_amount || order.payment_amount
            // const refund_amount = 0.01
            let refundForm = {
                refund_status: RefundStatusEnum.PENDING,
                refund_time: new Date(),
                refund_reason,
                refund_amount
            }
            // 更新订单状态
            await order.update(refundForm, { transaction });

            await transaction.commit();

            return true;
        } catch (error) {
            await transaction.rollback();
            throw error;
        }
    }

    /**
     * 处理退款
     */
    async refundConfirm(data) {
        const { id, refund_remark, refund_amount, approve } = data;

        // 查询订单
        const order = await this.ctx.model.Business.TravelOrder.findOne({
            where: { id }
        });

        if (!order) {
            throw new Error('订单不存在');
        }
        if (!approve) {
            // 不同意退款
            await order.update({
                refund_status: RefundStatusEnum.FAILED,
                refund_time: new Date(),
                refund_remark,
            });
            return true
        } 

        /**
         * 同意退款
         */
        let refund_amount_int = Number(refund_amount)
        if (refund_amount_int === 0) {
            throw new Error('退款金额不能为0');
        }
        if (isNaN(refund_amount_int)) {
            throw new Error('退款金额不正确');
        }
        console.log('refund_amount_int', refund_amount_int)
        console.log('order.payment_amount', order.payment_amount)
        // 同意退款
        if (refund_amount_int > order.payment_amount) {
            throw new Error('退款金额不能大于实付金额');
        }

       // 创建事务处理退款
        await order.update({
            refund_status: RefundStatusEnum.REFUNDING,
        });
        // 调用退款接口
        await this.ctx.service.business.travelOrderRefund.processRefund({
                order_no: order.order_no,
                refund_remark,
                refund_amount: refund_amount_int,
                payment_amount: order.payment_amount
        });
        return true
    }

    /**
     * 确认旅游行程
     * @param {Object} params - 参数
     * @return {Promise<boolean>}
     */
    async confirmTravel(params) {
        const { id, confirm_remark } = params;
        const transaction = await this.ctx.model.transaction();

        try {
            // 查询订单
            const order = await this.ctx.model.Business.TravelOrder.findOne({
                where: { id }
            });

            if (!order) {
                throw new Error('订单不存在');
            }

            // 判断订单状态
            if (order.status !== OrderStatusEnum.PAID) {
                throw new Error('只有待确认的订单才能确认行程');
            }

            // 更新订单状态
            await order.update({    
                status: OrderStatusEnum.SHIPPED,
                update_time: new Date(),
            }, { transaction });

            await transaction.commit();
            return true;
        } catch (error) {
            await transaction.rollback();
            throw error;
        }
    }

    /**
     * 完成旅游行程
     * @param {Object} params - 参数
     * @return {Promise<boolean>}
     */
    async completeTravel(params) {
        const { id, complete_remark } = params;
        const transaction = await this.ctx.model.transaction();

        try {
            // 查询订单
            const order = await this.ctx.model.Business.TravelOrder.findOne({
                where: { id },
                include: [
                    {
                        model: this.ctx.model.Business.User,
                        as: 'user',
                        attributes: ['nickname']
                    },
                    {
                        model: this.ctx.model.Business.User,
                        as: 'shareUser',
                        attributes: ['nickname', 'status']
                    },
                ]
            });

            if (!order) {
                throw new Error('订单不存在');
            }

            // 判断订单状态
            if (order.status !== OrderStatusEnum.SHIPPED) {
                throw new Error('只有已确认的订单才能完成行程');
            }

            // 更新订单状态
            await order.update({
                status: OrderStatusEnum.COMPLETED,
                update_time: new Date(),
            }, { transaction });
            // 增加销量
            await this.ctx.model.Business.Travel.update({
                sales: this.ctx.model.Sequelize.literal(`sales + 1`)
            }, {
                where: {
                    id: order.travel_id
                },
                transaction
            })
            // 增加佣金
            await this.addShareAmount(order, transaction)
            await transaction.commit();
            return true;
        } catch (error) {
            await transaction.rollback();
            throw error;
        }
    }

    /**
     * 增加佣金
     */
    async addShareAmount(order, transaction) {
        // 创建分销记录
        if (order.shareUser && order.shareUser.status === 1) {
            const travelOrderItems = await this.ctx.model.Business.TravelOrderItem.findAll({
                where: {
                    travel_order_id: order.id,
                    refund_status: RefundStatusEnum.DEFAULT
                }
            })
            const balanceRecordNo = generateTravelOrderNo('FX')
            let share_amount = 0
            let adult_count = travelOrderItems.filter(item => item.traveler_type === 'adult').length
            let child_count = travelOrderItems.filter(item => item.traveler_type === 'child').length
            if (order.travel_share_price && adult_count > 0) {
                share_amount += parseFloat(order.travel_share_price) * adult_count
            }
            if (order.travel_share_price2 && child_count > 0) {
                share_amount += parseFloat(order.travel_share_price2) * child_count
            }
            // 余额记录增加
            await this.ctx.model.Business.BalanceRecord.create({
                order_no: balanceRecordNo,
                out_bill_no: order.order_no,
                user_id: order.travel_share_user_id,
                amount: share_amount,
                amount2: 0,
                from_user_id: order.user_id,
                type: BalanceLogTypeEnum.DISTRIBUTOR_INCOME,
                description: `来自【${order.user.nickname}】的旅游订单，佣金收入`,
            }, { transaction })
            // 更新用户余额
            await this.ctx.model.Business.User.update({
                balance: this.ctx.model.Sequelize.literal(`balance + ${share_amount}`)
            }, {
                where: {
                    id: order.travel_share_user_id
                },
                transaction
            })
        }
        
    }

    /**
     * 减少佣金
     */
    async reduceShareAmount(order) {
        if (order.status !== OrderStatusEnum.COMPLETED) {
            return
        }
        const shareUser = await this.ctx.model.Business.User.findOne({
            where: {
                id: order.travel_share_user_id,
                status: 1
            }
        })
        const user = await this.ctx.model.Business.User.findOne({
            where: {
                id: order.user_id,
            }
        })
        const travelOrderItems = await this.ctx.model.Business.TravelOrderItem.findAll({
            where: {
                travel_order_id: order.id,
                refund_status: RefundStatusEnum.DEFAULT
            }
        })
        let share_amount = 0
        let adult_count = travelOrderItems.filter(item => item.traveler_type === 'adult').length
        let child_count = travelOrderItems.filter(item => item.traveler_type === 'child').length
        if (order.travel_share_price && adult_count > 0) {
            share_amount += parseFloat(order.travel_share_price) * adult_count
        }
        if (order.travel_share_price2 && child_count > 0) {
            share_amount += parseFloat(order.travel_share_price2) * child_count
        }
        
        if (shareUser && user) {
            // 创建事务
            const transaction = await this.ctx.model.transaction();
            try {
                // 减少佣金
                await this.ctx.model.Business.BalanceRecord.create({
                    order_no: generateTravelOrderNo('FX'),
                    out_bill_no: order.order_no,
                    user_id: order.travel_share_user_id,
                    amount: -share_amount,
                    amount2: 0,
                    from_user_id: order.user_id,
                    type: BalanceLogTypeEnum.DISTRIBUTOR_INCOME,
                    description: `来自【${user.nickname}】的旅游订单，订单退款，佣金收入扣减`,
                }, { transaction })
                // 减少用户余额
                await this.ctx.model.Business.User.update({
                    balance: this.ctx.model.Sequelize.literal(`balance - ${share_amount}`)
                }, {
                    where: {
                        id: order.travel_share_user_id
                    },
                    transaction
                })
                await transaction.commit();
            } catch (error) {
                await transaction.rollback();
                throw error;
            } 
        }
    }

    /**
     * 删除旅游订单
     * @param {Object} params - 参数
     * @return {Promise<boolean>}
     */
    async delete(params) {
        const { id } = params;
        // 查询订单
        const order = await this.model.findOne({
            where: { id }
        });

        if (!order) {
            throw new Error('订单不存在');
        }

        // 只有已取消、已退款的订单可以删除
        if (![OrderStatusEnum.CANCELLED].includes(order.status)) {
            throw new Error('只有已取消的订单才能删除');
        }
        // 软删除订单
        await super.delete(id, 0)
        return true;
    }
}

module.exports = TravelOrderService;
